<template>
	<view class="billing_content">
        <view class="billing_form">
            <uni-forms ref="form" :modelValue="formData" label-width="90">
                <uni-row class="form_row">
                    <uni-col class="form_item" :span="6">
                        <uni-forms-item class="form_input" label="客户:" name="khname">
                            <input type="text" disabled v-model="formData.khname" />
                        </uni-forms-item>
                    </uni-col>
                    <uni-col class="form_item" :span="6">
                        <uni-forms-item class="form_input" label="欠款:" name="qqk">
                            <input type="text" disabled v-model="formData.qqk" />
                        </uni-forms-item>
                    </uni-col>
                    <uni-col class="form_item" :span="6">
                        <uni-forms-item class="form_input" label="制单人:" name="zhuser">
                            <input type="text" disabled v-model="formData.zhuser" />
                        </uni-forms-item>
                    </uni-col>
                    <uni-col class="form_item" :span="6">
                        <uni-forms-item class="form_input" label="单据日期:" name="zhdate">
                            <uni-datetime-picker disabled type="date" :clear-icon="false" v-model="formData.zhdate" />
                        </uni-forms-item>
                    </uni-col>
                </uni-row>

                <uni-row class="form_row">
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="业务员:" name="ywy">
                            <input type="text" v-model="formData.ywy" placeholder="请输入业务员" />
                        </uni-forms-item>
                    </uni-col>
                    <!-- <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="仓库:" name="ck">
                            <uni-data-select
                                v-model="formData.ck"
                                :localdata="range"
                                placeholder="请选择仓库"
                            ></uni-data-select>
                        </uni-forms-item>
                    </uni-col> -->
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="托运方式:" name="tyfs">
                            <uni-data-select
                                class="form_input"
                                v-model="formData.tyfs"
                                :localdata="tyfsList"
                                placeholder="请选择托运方式"
                            ></uni-data-select>
                        </uni-forms-item>
                    </uni-col>
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="交货日期:" name="jh_date">
                            <uni-datetime-picker type="date" :clear-icon="false" v-model="formData.jh_date" />
                        </uni-forms-item>
                    </uni-col>
                </uni-row>

                <uni-row class="form_row">
                    <uni-col class="form_item" :span="24">
                        <uni-forms-item class="form_input" label="托运地址:" name="shaddr">
                            <input type="text" v-model="formData.shaddr" placeholder="请输入托运地址" />
                        </uni-forms-item>
                    </uni-col>
                </uni-row>

                <uni-row class="form_row">
                    <!-- <uni-col class="form_item" :span="16">
                        <uni-forms-item class="form_input" label="运号:" name="yunhao">
                            <input type="text" v-model="formData.yunhao" placeholder="请输入运号" />
                        </uni-forms-item>
                    </uni-col> -->
                     
                </uni-row>

                <uni-row class="form_row">
                    <uni-col class="form_item" :span="16">
                        <uni-forms-item class="form_input" label="备注:" name="remark">
                            <textarea style="height: 80rpx; width: 100%;" type="text" :maxlength="-1" v-model="formData.remark" placeholder="请输入备注" />
                        </uni-forms-item>
                    </uni-col>
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="附件:" name="attach">
                            <button v-if="!formData.attach" @click="updateImg">添加图片</button>
                            <view v-if="formData.attach" class="img_box">
                                <image style="width: 100%; height: 100%;" :src="formData.attach" />
                                <text @click="formData.attach = ''" class="iconfont icon-jian1"></text>
                            </view>
                        </uni-forms-item>
                    </uni-col>
                </uni-row>

                <uni-row class="form_row">
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="本次收款:" name="amount">
                            <input type="number" v-model="formData.amount" placeholder="请输入本次收款" />
                        </uni-forms-item>
                    </uni-col>
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="优惠金额:" name="discount">
                            <input type="number" v-model="formData.discount" placeholder="请输入优惠金额" />
                        </uni-forms-item>
                    </uni-col>
                    <uni-col class="form_item" :span="8">
                        <uni-forms-item class="form_input" label="收款方式:" name="lkfs">
                            <uni-data-select
                                class="form_input"
                                v-model="formData.lkfs"
                                :localdata="skfsList"
                                placeholder="请选择收款方式"
                            ></uni-data-select>
                        </uni-forms-item>
                    </uni-col>
                </uni-row>
            </uni-forms>
            
            <view class="form_footer">
                <view class="footer_text">
                    数量：
                    <text>{{ khInfo.gxSl || 0 }}</text>
                    款/
                    <text>{{ khInfo.totalSl || 0 }}</text>
                    件  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 合计
                    <text>￥ {{ khInfo.totalPrice || 0 }}</text>
                </view>
                <view>
                    <button :disabled="subDisabled" hover-class="hover_btn" @click="submitForm">提交订单</button>
                </view>
            </view>
        </view>

        <view style="flex: 1; overflow: auto;">
            <billingTableDetail @childChangeGwcInfo="childChangeGwcInfo" :list="billingList"></billingTableDetail>
        </view>
	</view>
</template>

<script>
import billingTableDetail from "@/components/billing-table-detail/billing-table-detail.vue";
import utils from "@/utils/utils.js";
import GetDate from "@/utils/date.js";
import Http from '@/service/api'
import { mapState, mapMutations } from 'vuex';
	export default {
		components: {
            billingTableDetail,
		},
		data() {
			return {
				statusBarHeight: 0,
                dk: uni.getStorageSync('baseUrl'),
                range: [
                    { value: 0, text: "篮球" },
                    { value: 1, text: "足球" },
                    { value: 2, text: "游泳" },
                ],
                tyfsList: [],
                skfsList: [],
                formData: {
                    attach: ''
                },
                billingList: [],
                khInfo: {},
                subDisabled: false,
			}
		},
        computed: {
        },
		onLoad(r) {
            if (r.hasOwnProperty('khInfo')) {
                this.khInfo = JSON.parse(r.khInfo)
                console.log('== khInfo ', this.khInfo)
                this.formData.khname = this.khInfo.name
                this.formData.khid = this.khInfo.bh
                this.formData.qqk = this.khInfo.qkje
                this.formData.shaddr = this.khInfo.shaddr 
                this.formData.ywy = this.khInfo.ywy 
                this.formData.remark = this.khInfo.remark 
            }

            this.formData.zhdate = GetDate.getToday().time;
            this.formData.jh_date = GetDate.getToday().time;

            this.formData.zhuser = uni.getStorageSync('loginUserName');
            let LoginType = uni.getStorageSync('loginData').LoginType
            let arr = uni.getStorageSync(`${LoginType}Cart`)

            let list = this.filterCheckFn(arr)
            this.billingList = list
            console.log('== list ', list)

            console.log('== 旧 ', utils.getTableData())
            this.GetBaseInfoList()
		},
		methods: {
            updateImg() {
                uni.chooseImage({
                    count: 1, // 最多选择1张图片
                    success: (res) => {
                        this.formData.attach = res.tempFilePaths[0]
                    },
                });
            },
            submitForm() {

                let LoginType = uni.getStorageSync('loginData').LoginType
                let list = uni.getStorageSync(`${LoginType}Cart`)
                // console.log('== 缓存中数据 ', list)

                let param =
                
                {
                    ...this.formData,
                    xdHuohaoDetail: {
                        data: this.billingList,
                    }
                }

                console.log('== param ', param)
                this.subDisabled = true

                // uni.navigateBack({
                //     delta: 1
                // });
                // let c = this.clearCart(list, this.billingList)
                // this.addCart_x(c)


                // return
                Http.GetOrderDdMx(JSON.stringify(param)).then(r => {
                    console.log('== r 保存 ', r)
                    let ModulePrimaryKey = r // XS250100002

                    uni.showToast({
                        title:'保存成功',
                        icon:'none',
                        duration:2000
                    })

                    let param1 = {
                        Module: '销售订单附件上传',
                        ModulePrimaryKey,
                        sort: 0,
                        IsMain: 1,
                        customId: uni.getStorageSync('customId'),
                    }

                    console.log('== 图片 ', param1)
                    console.log('== img ', this.formData.attach)

                    let _this = this
                    if (!this.formData.attach) {
                        setTimeout(() => {
                            uni.navigateBack({
                                delta: 1
                            });
                            let c = _this.clearCart(list, _this.billingList)
                            _this.addCart_x(c)
                        }, 2000)
                        return
                    }

                    uni.uploadFile({
                        url: `https://${this.dk}/BaseInfo/SysHuohao/UploadAdd.aspx`,
                        filePath: this.formData.attach, //从调用页面传入 --path: imgbox, 选取图片的地址数组  
                        name: 'img',
                        formData: {
                            Module: '销售订单附件上传',
                            ModulePrimaryKey,
                            sort: 0,
                            IsMain: 1,
                            customId: uni.getStorageSync('customId'),
                        },
                        header: {
                            "Content-Type": "multipart/form-data",
                            "Authorization": 'Bearer ' + uni.getStorageSync('token'),
                        },
                        success: (r) => {
                            console.log('== img r ', r)
                            if (r.statusCode == 200) {
                                console.log('== img r.data ', r.data)
                                let data = JSON.parse(r.data)
                                console.log('== data ---- ', data)
                                    uni.showToast({
                                        title:'图片上传成功',
                                        icon:'none',
                                        duration:3000
                                    })
                                    setTimeout(() => {
                                        uni.navigateBack({
                                            delta: 1
                                        });
                                    }, 2000)
                                    let c = _this.clearCart(list, _this.billingList)
                                    _this.addCart_x(c)
                            }
                            
                        },
                        fail: (err) => {
                            console.log('== img err ', err)
                            this.subDisabled = false
                            uni.showToast({
                                title:'图片上传失败',
                                icon:'none',
                                duration:3000
                            })
                        }
                    })

                }).catch(err => {
                    uni.showToast({
						title:err.message,
						icon:'none',
						duration:3000
					})
                    this.subDisabled = false
                })
            },

             // 获取基础数据
             GetBaseInfoList() {
                let param = { param: 'tyfs,skfs' }
                Http.GetBaseInfoList(param).then(r => {
                   console.log('== 11 基础数据 ', r)
                   this.tyfsList = r.tyfs.map(i => ({...i, value: i.name, text: i.name}))
                   this.skfsList = r.skfs.map(i => ({...i, value: i.bh, text: i.name}))
                   
                }).catch(err => {
                    console.log('== err ', err)
                })
            },

            childChangeGwcInfo(param) {
                let billingList = JSON.parse(JSON.stringify(this.billingList))
                let list = this.updateArray(billingList, param)
                this.billingList = list
                console.log('== 233 ', this.billingList)
            },


            // 、、、、 函数
            // 修改数据 
            updateArray(arr, obj) {
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i].main.huohao === obj.main.huohao) {
                        arr[i] = obj;
                    }
                }
                arr = arr.map(i => ({
                    ...i,
                    colorTable: this.transformArr(i.colorList)
                }))
                return arr;
            },

            clearCart(arr, arr2) {
                for (let i = 0; i < arr.length; i++) {
                    for (let j = 0; j < arr2.length; j++) {
                        if (arr[i].main.uuid_1 === arr2[j].main.uuid_1) {

                            for(let k = 0; k < arr[i].colorList.length; k++) {
                                for(let o = 0; o < arr2[j].colorList.length; o++) {

                                    if (
                                        arr[i].colorList[k].chima == arr2[j].colorList[o].chima &&
                                        arr[i].colorList[k].color == arr2[j].colorList[o].color &&
                                        arr[i].colorList[k].huohao == arr2[j].colorList[o].huohao 
                                        ) {
                                            arr[i].colorList[k].num -=  arr2[j].colorList[o].num

                                            for(let m = 0; m < arr[i].colorList[k].chimaList.length; m++) {
                                                for(let n = 0; n < arr2[j].colorList[o].chimaList.length; n++) {
                                                    if (
                                                        // arr[i].colorList[k].chimaList[m].chima == arr2[j].colorList[o].chimaList[n].chima &&
                                                        // arr[i].colorList[k].chimaList[m].color == arr2[j].colorList[o].chimaList[n].color &&
                                                        // arr[i].colorList[k].chimaList[m].huohao == arr2[j].colorList[o].chimaList[n].huohao 
                                                        arr[i].colorList[k].chimaList[m].uuid_1 == arr2[j].colorList[o].chimaList[n].uuid_1
                                                        ) {
                                                            arr[i].colorList[k].chimaList[m].num -=  arr2[j].colorList[o].chimaList[n].num
                                                    }
                                                }
                                            }
                                    }
                                }
                            }
                          
                        }
                    }

                      // 减去 hjsl 和 hjPrice
                    arr[i].hjsl = arr[i].colorList.map(k => ({...k, num: k.chimaList.reduce((total, color) => total + color.num, 0)})).reduce((total, color) => total + color.num, 0)
                    arr[i].hjPrice = arr[i].hjsl * arr[i].main.xsprice;
                }

                arr = arr.filter(item => item.hjsl)
                return arr;
            },



            // 筛选出选中的项
            filterCheckFn(arr) {
                // let LoginType = uni.getStorageSync('loginData').LoginType
                // let arr = uni.getStorageSync(`${LoginType}Cart`)

                arr.forEach(item => {
                    // 遍历 colorList
                    item.colorList.forEach(colorItem => {
                        // 遍历 colorItem.chimaList
                        colorItem.chimaList = colorItem.chimaList.map(chimaItem => {
                            // 检查是否匹配
                            if ( !chimaItem.check ) {
                                // 如果匹配，删除该项，返回 false
                                return {...chimaItem, num: 0, ddid: '', chimaid: ''};
                            }
                            return {...chimaItem, num: chimaItem.num, ddid: '', chimaid: ''}; // 如果不匹配，保留该项
                        });
                        colorItem.num =  colorItem.chimaList.reduce((sum, chima) => sum + chima.num, 0);
                    });
                    

                    item.colorList = item.colorList.filter(i => !i.chimaList.every(j => j.num == 0))

                    item.colorList = item.colorList.filter(i => i.chimaList.length)
                    item.showTable = false
                    item.colorTable = this.transformArr(item.colorList)

                    // 更新 hjsl（colorList 中所有 num 的总和）
                    item.hjsl = item.colorList.reduce((total, color) => total + color.num, 0);

                    // 更新 hjPrice（hjsl * xsprice）
                    item.hjPrice = item.hjsl * item.main.xsprice;
                });
                // 删除 colorList 为空的对象

                let a = arr.filter(item => item.colorList.length)
                return a;
            },
            // 将数组 转换成 table 形式
            transformArr(arr) {
                return arr.map(item => {
                    // 创建一个新的对象
                    let transformedItem = {
                        hj: item.num,  // 直接提取 num 作为 hj
                        color: item.color,
                        chima: {}  // 初始化一个空对象，用于存放尺寸和对应的数量
                    };

                    // 遍历 chimaList，并填充 transformedItem.chima
                    item.chimaList.forEach(chima => {
                        transformedItem.chima[chima.chima] = chima.num;
                    });

                    return transformedItem;
                });
            },
            ...mapMutations([
                "addCart_x",
            ]),
		}
	}
</script>

<style lang="less" scoped>
.billing_content {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background: #fff;
    font-size: 16rpx;

    .billing_form {
        padding: 15rpx 20rpx;
        border-bottom: 1rpx solid #ccc;
        background: #fff;

        .form_row {
            width: 100%;
            .uni-forms-item {
                align-items: center;
            }
        }
        .form_item {
            display: flex;
            align-items: center;

            .label {
                white-space: nowrap;
            }
            .form_input {
                flex: 1;
                
                .img_box {
                    position: relative;
                    width: 100%;
                    height: 80rpx;

                    .iconfont {
                        position: absolute;
                        top: 0;
                        left: 0;
                        color: red;
                        font-size: 30rpx;
                    }
                }

                button {
                    color: #ffac60;
                }
            }
        }

        .form_footer {
            display: flex;
            align-items: center;
            font-size: 20rpx;
            border-top: 1rpx solid #ccc;
            padding-top: 10rpx;

            .footer_text {
                flex: 1;

                text {
                    color: #ffac60;
                    padding: 0 10rpx;
                }
            }

            button {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 120rpx;
                background: #ffac60;
                color: #fff;
                margin: 0;
            }
            .hover_btn {
                background: #e49a55;
            }

        }
        
    }
	
}
</style>
